﻿using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Ymatou.Evaluate.Common.UnityIOC
{
    public sealed class RegisterTypes
    {
        public static void Register(IUnityContainer container, Assembly assembly)
        {
            Register(container, new Assembly[] { assembly });
        }

        public static void Register(IUnityContainer container, IEnumerable<Assembly> assemblys)
        {
            Dictionary<Type, Type> types = new Dictionary<Type, Type>();

            assemblys.ToList().ForEach(_assembly =>
                AppDomain.CurrentDomain.GetAssemblies().Where(o => o.Equals(_assembly)).ToList().ForEach(o =>
                {
                    o.GetTypes().Where(t => t.IsClass && !t.IsAbstract && !t.IsSealed).ToList().ForEach(t =>
                    {
                        var It = t.GetInterfaces().Where(it => !it.IsGenericType && assemblys.Contains(it.Assembly)).FirstOrDefault();
                        if (It != null)
                        {
                            container.RegisterType(It, t);
                            types.Add(It, t);
                        }
                    });
                }));
        }

    }
}
